<template>
  <div>
    <window
      :show="windowConfig.show"
      :buttons="windowConfig.buttons"
      @close="closeWindow"
    >
      <el-form :model="formData" :rules="rules1" ref="formDataRef">
        <el-form-item prop="title">
          <div class="title-input">
            <el-input
              placeholder="请输入博客标题"
              v-model.trim="formData.title"
              size="large"
            >
            </el-input>
          </div>
        </el-form-item>
        <el-form-item prop="content">
          <div class="markdownContent" :style="{ width: '100%' }">
            <EditorHtml
              v-if="formData.editorType === 0"
              :height="editorHtmlHeight"
              v-model="formData.content"
              >{{ formData.editorType }}</EditorHtml
            >
            <EditorMarkdown
              v-else
              :height="editorMarkdownHeight"
              v-model="formData.markdownContent"
              @htmlContent="setHtmlContent"
            ></EditorMarkdown>
          </div>
        </el-form-item>
      </el-form>

      <!-- <EditorMarkdown :height="editorMarkdownHeight"></EditorMarkdown> -->
      <!-- <EditorHtml :height="editorHtmlHeight"></EditorHtml> -->
    </window>
  </div>
</template>

<script setup>
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getCurrentInstance,
  nextTick,
  onMounted,
  onUnmounted,
  reactive,
  ref,
} from "vue";
// <EditorMarkdown :height="editorHeight"></EditorMarkdown>
const { proxy } = getCurrentInstance();

const api = {
  loadCategoryList: "/category/loadAllCategory4Blog",
  saveCategory: "category/saveCategory4Blog",
  delCategory: "/category/delCategory4Blog",
  saveBlog: "blog/saveBlog4Special",
  getUserInfo: "getUserInfo",
  getBlogDetail: "/blog/getBlogById",
  autoSave: "blog/autoSaveBlog4Special",
};

const init = (type, data) => {
  windowConfig.show = true;
  // console.log(data);
  nextTick(() => {
    // console.log(data);
    formDataRef.value.resetFields();
    formData.value = {};

    if (type === "add") {
      // 这些操作，修改是不需要的
      formData.value.categoryId = data.categoryId; // 属于哪个专题
      formData.value.pBlogId = data.blogId; // 父亲是谁
      // console.log(formData.value);
      // 新增的博客一定属于这个专题，那么就要设置好
      getUserInfo();
    } else {
      getBlogDetail(data.blogId);
    }
    startTimer();
  });
};

defineExpose({ init });

// 自动保存

let timer = ref(null);

const startTimer = () => {
  timer.value = setInterval(() => {
    autoSave();
  }, 5000);
};

const cleanTimer = () => {
  if (timer.value !== null) {
    clearInterval(timer.value);
    timer.value = null;
  }
};

const autoSave = async () => {
  // console.log(formData.value.content);
  // console.log(formData.value.markdownContent);
  if (
    (formData.value.title === "" && formData.value.content === "<p><br></p>") ||
    (formData.value.title === "" && formData.value.content === "") ||
    timer.value === null
  ) {
    return;
  }
  const params = {};
  Object.assign(params, formData.value);
  let result = await proxy.Request({
    url: api.autoSave,
    params: params,
  });
  if (!result) {
    return;
  }
  formData.value.blogId = result.data;
};

const getUserInfo = async () => {
  let result = await proxy.Request({
    url: api.getUserInfo,
  });
  if (!result) {
    return;
  }
  formData.value.editorType = result.data.editorType;
};
// 编辑器的高度
const editorMarkdownHeight =
  window.innerHeight - 60 - 20 - 30 - 50 - 10 - 30 - 65;
const editorHtmlHeight = window.innerHeight - 290 - 65;

const formDataRef = ref(null);
const formData = ref({ tag: [] });
const rules1 = {
  title: [{ required: true, message: "请输入博客标题" }],
  content: [{ required: true, message: "请输入博客内容" }],
};
const rules2 = {
  categoryId: [{ required: true, message: "请选择博客分类" }],
  type: [{ required: true, message: "请选择博客类型" }],
  allowComment: [{ required: true, message: "请选择是否允许评论" }],
  reprintUrl: [{ required: true, message: "请输入原文地址" }],
};

//博客分类
const categoryList = ref([]);
const loadCategoryList = async () => {
  let result = await proxy.Request({
    url: api.loadCategoryList,
  });
  if (!result) {
    return;
  }
  categoryList.value = result.data;
};
onMounted(() => {
  loadCategoryList();
});
onUnmounted(() => {
  cleanTimer();
});

// window 新增，取消

const windowConfig = reactive({
  show: false,
  title: "标题",
  buttons: [
    {
      type: "danger",
      text: "确定",
      click: (e) => {
        submitBlog();
      },
    },
  ],
});

// 关闭编辑博客的界面并刷新
const emit = defineEmits();
const closeWindow = () => {
  windowConfig.show = false;
  emit("callback", formData.value);
  if (timer.value !== null) {
    cleanTimer();
  }
};

// 修改或新增博客
const showEditBlog = (type, data) => {
  windowConfig.show = true;
};

const getBlogDetail = async (blogId) => {
  let result = await proxy.Request({
    url: api.getBlogDetail,
    params: {
      blogId: blogId,
    },
  });
  if (!result) {
    return;
  }
  // console.log(result.data);
  formData.value = result.data;
  if (result.data.tag) {
    formData.value.tag = result.data.tag.split("|");
  } else {
    formData.value.tag = [];
  }

  // console.log(formData.value);
};

// markdown编辑器设置html内容
const setHtmlContent = (htmlContent) => {
  formData.value.content = htmlContent;
};

const submitBlog = () => {
  formDataRef.value.validate(async (valid) => {
    if (!valid) {
      return;
    }
    let params = formData.value;
    let result = proxy.Request({
      url: api.saveBlog,
      params: params,
    });
    if (!result) {
      return;
    }
    windowConfig.show = false;
    cleanTimer();
    emit("callback", params);
    // console.log(result);
  });
};
</script>

<style lang="scss" scoped>
.title-input {
  width: 100%;
  border-bottom: 1px solid #ddd;
}
.title-input :deep(.el-input__wrapper) {
  background-color: #ffffff;
  box-shadow: 0 0 0 0;
  font-size: 18px;
}
</style>
